package com.yasha.sharingnews;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.TypedArray;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.agimind.widget.SlideHolder;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.yasha.adapter.ListChuyenMucAdapter;
import com.yasha.customview.*;
import com.yasha.ulti.Tools;

public class MainPageActivty extends SherlockActivity implements
		OnMapLongClickListener  , OnMarkerClickListener{

	private String TAG = "MainPageActivity";
	private GoogleMap map;
	public static String IDString = "";

	private ProgressDialog ringProgressDialog;
	private SlideHolder sildingLayout;

	private ActionBar actionBar;
	private Bundle extras;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (Tools.getConnectivityStatus(this) == Tools.TYPE_NOT_CONNECTED) {
			ShowConnectErrorDialog(R.string.connect_error_title,
					R.string.no_internet_access);
		} else {

			IDString = Tools.loadSavedPreferences(this,
					Tools.sharePreferencesUserKey, Tools.UserIDkey);
			extras = getIntent().getExtras();
			if (IDString.equals("") && extras != null) {
				// Send Request get IDString

				ringProgressDialog = ProgressDialog.show(MainPageActivty.this,
						null, null);
				ringProgressDialog.setCancelable(false);

				createUserIDString();
			} else {
				createActionBarViewAndSlidingMenu();
				showUI();
			}
		}
	}

	private void createUserIDString() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				UserController userCL = new UserController();
				String username = extras.getString("username");
				String phone = extras.getString("phone");
				if (!username.equals("") && !phone.equals("")) {
					IDString = userCL.addUserToServer(username, phone);
				}
				runOnUiThread(new Runnable() {

					@Override
					public void run() {

						if (ringProgressDialog.isShowing()
								&& ringProgressDialog != null) {
							ringProgressDialog.dismiss();
							ringProgressDialog = null;
						}
						if (IDString.equals("")) {
							ShowConnectErrorDialog(
									R.string.request_error_title,
									R.string.request_add_user_error);
						} else {
							boolean saveDataResult = Tools.savePreferences(
									MainPageActivty.this,
									Tools.sharePreferencesUserKey,
									Tools.UserIDkey, IDString);
							if (saveDataResult) {
								createActionBarViewAndSlidingMenu();
								showUI();
							} else {
								ShowConnectErrorDialog(
										R.string.request_error_title,
										R.string.request_add_user_id_to_app_data);
							}

						}
					}
				});

			}
		}).start();
	}

	private void createActionBarViewAndSlidingMenu() {
		// Create Action Bar View
		actionBar = getSupportActionBar();

		// Create Sliding Menu View
		sildingLayout = (SlideHolder) findViewById(R.id.slideHolder);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.action_items, menu);
		return true;
	}

	private MenuItem menuItem;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		RelativeLayout left = (RelativeLayout) findViewById(R.id.left_sliding);
		RelativeLayout right = (RelativeLayout) findViewById(R.id.right_sliding);

		switch (item.getItemId()) {
		case R.id.menu_search:
			menuItem = item;
			Tools.Log(TAG, "Menu Search");
			if (!sildingLayout.isOpened()) {
				sildingLayout.setDirection(SlideHolder.DIRECTION_LEFT);
				right.setVisibility(View.GONE);
				left.setVisibility(View.VISIBLE);
				sildingLayout.toggle();
			}
			break;
		case R.id.menu_post:
			menuItem = item;
			Tools.Log(TAG, "Menu Post");

			break;
		case R.id.menu_mail:
			menuItem = item;
			Tools.Log(TAG, "Menu Mail");
			if (!sildingLayout.isOpened()) {
				sildingLayout.setDirection(SlideHolder.DIRECTION_RIGHT);
				right.setVisibility(View.VISIBLE);
				left.setVisibility(View.GONE);
				sildingLayout.toggle();
			}
			break;
		default:
			break;
		}
		return true;
	}

	private void showUI() {
		// Get a handle to the Map Fragment
		map = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.fragment_detail_map)).getMap();

		map.setMyLocationEnabled(true);
		LatLng defaultLocation = new LatLng(10.786857, 106.660924);

		map.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 18));

		map.setOnMapLongClickListener(this);
		map.setOnMarkerClickListener(this);
		Marker melbourne = map.addMarker(new MarkerOptions()
				.position(defaultLocation).title("Default Position")
				.snippet("Welcome you using our App"));

		showChuyenMucDialog();
	}

	// Chuyen Muc items
	private String[] navChuyenMucTitles;
	private TypedArray navChuyenMucIcons;

	private void showChuyenMucDialog() {
		// Create Data for Chuyen Muc
		final ArrayList<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();

		navChuyenMucTitles = getResources().getStringArray(
				R.array.array_chuyen_muc_items);

		// nav drawer icons from resources
		navChuyenMucIcons = getResources().obtainTypedArray(
				R.array.array_chuyen_muc_icons);

		for (int i = 0; i < navChuyenMucTitles.length; i++) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("name", navChuyenMucTitles[i]);
			data.put("img", navChuyenMucIcons.getResourceId(i, -1) + "");
			datas.add(data);
			Tools.Log(TAG, "add  data  : " + i);
		}
		Tools.Log(
				TAG,
				"Data  size : " + datas.size() + " : "
						+ navChuyenMucTitles.length + " : "
						+ navChuyenMucIcons.length());
		// Create Chuyen Muc View
		LayoutInflater inflater = getLayoutInflater();
		View dialoglayout = inflater.inflate(R.layout.dialog_chuyen_muc,
				(ViewGroup) getCurrentFocus());
		dialoglayout.setBackgroundResource(android.graphics.Color.TRANSPARENT);
		ListView listView = (ListView) dialoglayout
				.findViewById(R.id.list_chuyen_muc);
		ListChuyenMucAdapter adapter = new ListChuyenMucAdapter(this, datas);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// Chuyen Muc Click
				Tools.Log(TAG, "listView click item index : " + position);
				switch (position) {
				case 0:
					// Chuyen muc 1
					break;
				case 1:
					// Chuyen muc 2
					break;
				case 2:
					// Chuyen muc 3
					break;
				case 3:
					// Chuyen muc 4
					break;
				case 4:
					// Chuyen muc 5
					break;
				case 5:
					// Chuyen muc 6
					break;
				case 6:
					// Chuyen muc 7
					break;
				case 7:
					// Chuyen muc 8
					break;
				default:
					break;
				}
			}

		});

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(null);
		builder.setView(dialoglayout);
		builder.setCancelable(true);

		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	private void ShowConnectErrorDialog(int TitleID, int MsgID) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(TitleID);
		builder.setMessage(MsgID);
		builder.setCancelable(false);
		builder.setNegativeButton(getString(R.string.quit),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						MainPageActivty.this.finish();
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	@Override
	public void onMapLongClick(LatLng point) {
		// TODO Auto-generated method stub
		double longti = point.longitude;
		double lati = point.latitude;
		String city = "";
		try {
			Geocoder gcd = new Geocoder(MainPageActivty.this,
					Locale.getDefault());
			List<Address> addresses = gcd.getFromLocation(lati, longti, 1);
			if (addresses.size() > 0)
				city = addresses.get(0).getLocality();
		} catch (Exception e) {
			Tools.Log(TAG, "onMapLongClick error : " + e.toString());
		}

		Intent intent_post = new Intent(MainPageActivty.this,
				PostActivity.class);
		intent_post.putExtra("city", city);
		intent_post.putExtra("longti", longti);
		intent_post.putExtra("lati", lati);
		startActivity(intent_post);

	}

	@Override
	public boolean onMarkerClick(Marker mark) {
		// TODO Auto-generated method stub
		//usig getTitle of marker to catch the event !
		return false;
	}
}
